package com.fsd.admin.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.fsd.core.service.impl.BaseServiceImpl;
import com.fsd.core.bean.CheckTree;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.B_article;
import com.fsd.admin.model.B_subject;
import com.fsd.admin.model.B_subjectcheck;
import com.fsd.admin.model.Sys_PopedomAllocate;
import com.fsd.admin.service.B_articleService;
import com.fsd.admin.service.B_subjectService;
import com.fsd.admin.service.B_subjectcheckService;
import com.fsd.admin.dao.B_subjectcheckDao;

@Repository("b_subjectcheckServiceImpl")
public class B_subjectcheckServiceImpl extends BaseServiceImpl<B_subjectcheck, String> implements B_subjectcheckService{
    
    private static final Logger log = Logger.getLogger(B_subjectcheckServiceImpl.class);
    private String depict = "";
    
    @Resource(name = "b_subjectcheckDaoImpl")
	public void setBaseDao(B_subjectcheckDao B_subjectcheckDao) {
		super.setBaseDao(B_subjectcheckDao);
	}
	
	@Resource(name = "b_subjectcheckDaoImpl")
	private B_subjectcheckDao objectDao;

    @Resource(name = "b_subjectServiceImpl")
	private B_subjectService subjectService;
    
    @Resource(name = "b_articleServiceImpl")
	private B_articleService articleService;
	
	//检查类型
	/**
     * 栏目未更新
     */
	public static final String jclxlmwgx = "lmwgx";
	/**
     * 栏目关联人员，或管理人员
     */
	public static final String jclxlmglry = "lmglry";
	
	/**
	 * 根据检查类型获取相关数据集合
	 * @param companyid
	 * @param jclx
	 * @param baseid
	 * @return
	 */
	private List<B_subjectcheck> getObjectCheckByJclx(String companyid, String jclx, String baseid){
		Criteria c = objectDao.createCriteria();
        c.add(Restrictions.eq("companyid", companyid));
		c.add(Restrictions.eq("checktype", jclx));
		c.add(Restrictions.eq("baseid", baseid));
		return objectDao.getList(c);
	}
    
    /**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
        c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.add(Restrictions.eq("deleted", "0"));
		c.addOrder(Order.asc("adddate"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("title") != null && !"".equals(objectMap.get("title"))){
				c.add(Restrictions.like("title", "%" + objectMap.get("title") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
    
    /**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
	public void save(B_subjectcheck obj, A_Employee employee) throws Exception{
        if(obj.getId() != null && !"".equals(obj.getId())){
            //修改
            B_subjectcheck old_obj = objectDao.get(obj.getId());
            
            objectDao.update(old_obj);
        }else{
            //添加
            obj.setId(this.getUUID());//设置主键
			obj.setCompanyid(employee.getCompanyid());//所属单位
			objectDao.save(obj);
        }
    }
    
    /**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
		}
		String hql = "";
		objectDao.executeHql("update B_subjectcheck t set t.deleted = '1', t.updatedate = '" + this.getData() + 
				"', t.updateemployeeid = '" + employee.getId() + "', t.updateemployeename = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
	}
    
    /**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public B_subjectcheck getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		B_subjectcheck obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}


	//---------------------栏目未更新-------------------------//
	/**
	 * 获取树
	 * @param user
	 * @return
	 */
	public List<CheckTree> getObjectCheck(ParametersUtil parameters, A_Employee employee, 
			Map<String, List<String>> popdomMap) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}

		List<CheckTree> menulist = new ArrayList<CheckTree>();
		B_subject subject = this.subjectService.getObjectStructByID(
				objectMap.get("id").toString(), employee.getCompanyid());
		if (subject == null)
			return menulist;
		List<Object> list = subject.getList();
		if (list == null || list.size() == 0)
			return menulist;
		
		List<B_subjectcheck> objList = this.getObjectCheckByJclx(
				employee.getCompanyid(), jclxlmwgx, subject.getBaseid());
		Map<String, B_subjectcheck> subIDMap = new HashMap<String, B_subjectcheck>();
		for (B_subjectcheck obj : objList) {
			subIDMap.put(obj.getSubjectid(), obj);
		}
		
		CheckTree tree = null;
		B_subject obj = null;
		for (Object object : list) {
			obj = (B_subject) object;
			if (!B_subjectServiceImpl.lxztqy1.equals(obj.getStatuscode()))
				continue;
			tree = new CheckTree();
			if (subIDMap.containsKey(obj.getId()))
				tree.setChecked(true);
			else
				tree.setChecked(false);
			tree.setId(obj.getId());
			tree.setText(obj.getTitle());
			tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
			this.getCheckTreeStruct(tree, obj.getList(), subIDMap);
			menulist.add(tree);
		}
		return menulist;
	}
	/**
	 * 获得复选框结构
	 * @param isAdmin
	 * @param fTree
	 * @param list
	 */
	private void getCheckTreeStruct(CheckTree fTree, List<Object> list, Map<String, B_subjectcheck> subIDMap){
		fTree.setLeaf(true);
		if (list == null && list.size() == 0){
			return;
		}
		CheckTree tree = null;
		B_subject obj = null;
		for (Object object : list) {
			obj = (B_subject) object;
			if (!B_subjectServiceImpl.lxztqy1.equals(obj.getStatuscode()))
				continue;
			fTree.setLeaf(false);
			fTree.setExpanded(true);
			tree = new CheckTree();
			if (subIDMap.containsKey(obj.getId()))
				tree.setChecked(true);
			else
				tree.setChecked(false);
			tree.setId(obj.getId());
			tree.setText(obj.getTitle());
			tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
			this.getCheckTreeStruct(tree , obj.getList(), subIDMap);
			fTree.getChildren().add(tree);
		}
	}
	
	/**
	 * 栏目未更新，保存栏目选择
	 * @param parameters
	 * @throws Exception
	 */
	public void save_Subject(ParametersUtil parameters) throws Exception {
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("ids") == null){
			throw new BusinessException(depict + "获取缺少权限ID参数!");
		}
		if(objectMap.get("qxlx") == null){
			throw new BusinessException(depict + "获取缺少权限类型参数!");
		}
		//先清空当前角色的类型权限信息
		String qxlx = objectMap.get("qxlx").toString();
		objectDao.executeSql("delete from B_subjectcheck where CheckType = '" + qxlx + 
				"' and CompanyID = '" + objectMap.get("id") + "'");
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String qxid = objectMap.get("id").toString();

		//循环将新权限保存进去
		for (String id : dir) {
			B_subjectcheck obj = new B_subjectcheck();
			obj.setId(this.getUUID());
			obj.setCompanyid(qxid);
			obj.setChecktype(qxlx);
			String[] ids = id.split("--");
			obj.setSubjectid(ids[0]);
			obj.setBaseid(ids[1]);
			objectDao.save(obj);
		}
	}
	
	/**
	 * 检查更新结果
	 */
	@SuppressWarnings({ "unused", "unchecked", "rawtypes" })
	public List<Map<String, String>> getJcjgMap(ParametersUtil parameters, A_Employee employee) throws Exception {
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");
		double finDate = (Double) objectMap.get("finDate");
		SimpleDateFormat adateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar c = Calendar.getInstance();   
		c.setTime(new Date());      
		c.set(Calendar.DATE, c.get(Calendar.DATE) - (int)finDate);      
		Date fDate = c.getTime();
		if(idList.size()>0){
			for(String id : idList){
				String[] str = id.split("--");
				B_subject subject = subjectService.get(str[0]);
				if(subject != null){
					Map<String,String> map = new HashMap<String,String>();
					String leafpath = "根目录";
					String[] str1 = str[1].split("/");
					for(int i = 0;i<str1.length;i++){
						if(str1[i] != null){
							if(!str1[i].equals("")){
								if(!str1[i].equals("0")){
									leafpath += ">"+subjectService.get(str1[i]).getTitle();
								}
							}
						}
					}
					map.put("leafpath", leafpath);
					map.put("title", subject.getTitle());
					map.put("id", subject.getId());
					B_article article = articleService.getFinally(subject.getId());
					if(article!=null){
						Date aDate = adateFormat.parse(article.getAdddate());
						if(aDate.after(fDate)){
							Date date = adateFormat.parse(article.getAdddate());
							map.put("adddate",formatter.format(date));
							c.setTime(aDate);
							long time1 = c.getTimeInMillis();
							c.setTime(new Date());
							long time2 = c.getTimeInMillis();
							map.put("sjc",(time2-time1)/(1000*3600*24)+"");
							map.put("yonid", "1");
							map.put("yonname","已更新");
						}else{
							if(subject.getIsleaf().equals("false")){
								String[] lef = forleaf(subject.getId(),fDate, employee.getCompanyid());
								if(!lef[2].equals("该栏目下没有文章")){
								Date date = adateFormat.parse(lef[2]);
								lef[2] = formatter.format(date);}
								map.put("adddate",lef[2]);
								map.put("sjc",lef[3]);
								map.put("yonname",lef[0]);
								map.put("yonid",lef[1]);
							}
							else{
								Date date = adateFormat.parse(article.getAdddate());
								map.put("adddate",formatter.format(date));
								c.setTime(aDate);
								long time1 = c.getTimeInMillis();
								c.setTime(new Date());
								long time2 = c.getTimeInMillis();
								map.put("sjc",(time2-time1)/(1000*3600*24)+"");
								map.put("yonid", "0");
								map.put("yonname","未更新");
							}
						}
					}else{
						if(subject.getIsleaf().equals("false")){
							String[] lef = forleaf(subject.getId(),fDate, employee.getCompanyid());
							if(!lef[2].equals("该栏目下没有文章")){
								Date date = adateFormat.parse(lef[2]);
								lef[2] = formatter.format(date);}
							map.put("adddate",lef[2]);
							map.put("sjc",lef[3]);
							map.put("yonname",lef[0]);
							map.put("yonid",lef[1]);
						}
						else{
							map.put("adddate","该栏目下没有文章");
							map.put("sjc","0");
							map.put("yonid", "0");
							map.put("yonname","未更新");
						}
					}
					if(map.get("yonid").equals("0"))
						list.add(map);
				}
			}
		}
		return list;
	}
	/**
	 * 获取该栏目下没有文章
	 * @param id
	 * @param fDate
	 * @return
	 * @throws Exception
	 */
	private String[] forleaf(String id,Date fDate, String companyid) throws Exception{
		Calendar c = Calendar.getInstance();  
		String[] rstr = {"","","",""};
		SimpleDateFormat adateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
		List<B_subject> subjectList = subjectService.queryObjectListById(id, companyid);
		for(B_subject subject : subjectList){
			B_article article = articleService.getFinally(subject.getId());
			if(article!=null){
				Date aDate = adateFormat.parse(article.getAdddate());
				if(aDate.after(fDate)){
					rstr[2]=article.getAdddate();
					c.setTime(aDate);
					long time1 = c.getTimeInMillis();
					c.setTime(new Date());
					long time2 = c.getTimeInMillis();
					rstr[3] = (time2-time1)/(1000*3600*24)+"";
					rstr[0] = "已更新";
					rstr[1] = "1";
					return rstr;
				}else{
					if(subject.getIsleaf().equals("false")){
						rstr = forleaf(subject.getId(),fDate, companyid);
						if(rstr[0].equals("已更新")){
							rstr[1] = "1";
							return rstr;
						}
					}
				}
			}else{
				if(subject.getIsleaf().equals("false")){
					rstr = forleaf(subject.getId(),fDate, companyid);
					if(rstr[0].equals("已更新")){
						rstr[1] = "1";
						return rstr;
					}
				}
			}
			if(rstr[2].equals("")){
				Date aDate = adateFormat.parse(article.getAdddate());
				rstr[2]=article.getAdddate();
				c.setTime(aDate);
				long time1 = c.getTimeInMillis();
				c.setTime(new Date());
				long time2 = c.getTimeInMillis();
				rstr[3] = (time2-time1)/(1000*3600*24)+"";
			}else{
				Date aDate = adateFormat.parse(article.getAdddate());
				Date bDate = adateFormat.parse(rstr[2]);
				if(aDate.after(bDate)){
					rstr[2]=article.getAdddate();
					c.setTime(aDate);
					long time1 = c.getTimeInMillis();
					c.setTime(new Date());
					long time2 = c.getTimeInMillis();
					rstr[3] = (time2-time1)/(1000*3600*24)+"";
				}
			}
		}
		rstr[0] = "未更新";
		rstr[1] = "0";
		return rstr;
	}


	
	
	//---------------------栏目关联人员，或管理人员-------------------------//
	public List<CheckTree> getQxObjectCheck(ParametersUtil parameters, A_Employee employee, 
			Map<String, List<String>> popdomMap) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}

		List<CheckTree> menulist = new ArrayList<CheckTree>();
		B_subject subject = this.subjectService.getObjectStructByID(
				objectMap.get("id").toString(), employee.getCompanyid());
		if (subject == null)
			return menulist;
		List<Object> list = subject.getList();
		if (list == null || list.size() == 0)
			return menulist;
		ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");
		Map<String,List<B_subjectcheck>> idsMap = new HashMap<String, List<B_subjectcheck>>();
		List<B_subjectcheck> objList = this.getObjectCheckByJclx(
				employee.getCompanyid(), jclxlmglry, subject.getBaseid());
		Map<String, B_subjectcheck> subIDMap = new HashMap<String, B_subjectcheck>();
		for (B_subjectcheck obj : objList) {
			if(idList != null && !idList.equals("")){
				for(String str : idList){
					if(obj.getEmployeeid().equals(str)){
						if(!subIDMap.containsKey(str)){
							subIDMap.put(obj.getSubjectid(), obj);
						}
						
					}
				}
			}
		}
		
		CheckTree tree = null;
		B_subject obj = null;
		for (Object object : list) {
			obj = (B_subject) object;
			if (!B_subjectServiceImpl.lxztqy1.equals(obj.getStatuscode()))
				continue;
			tree = new CheckTree();
			if (subIDMap.containsKey(obj.getId()))
				tree.setChecked(true);
			else
				tree.setChecked(false);
			tree.setId(obj.getId());
			tree.setText(obj.getTitle());
			tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
			this.getCheckTree(tree, obj.getList(), subIDMap);
			menulist.add(tree);
		}
		return menulist;
	}
	/**
	 * 获得复选框结构
	 * @param isAdmin
	 * @param fTree
	 * @param list
	 */
	private void getCheckTree(CheckTree fTree, List<Object> list, Map<String, B_subjectcheck> subIDMap){
		fTree.setLeaf(true);
		if (list == null && list.size() == 0){
			return;
		}
		CheckTree tree = null;
		B_subject obj = null;
		for (Object object : list) {
			obj = (B_subject) object;
			if (!B_subjectServiceImpl.lxztqy1.equals(obj.getStatuscode()))
				continue;
			fTree.setLeaf(false);
			fTree.setExpanded(true);
			tree = new CheckTree();
			if (subIDMap.containsKey(obj.getId()))
				tree.setChecked(true);
			else
				tree.setChecked(false);
			tree.setId(obj.getId());
			tree.setText(obj.getTitle());
			tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
			this.getCheckTree(tree , obj.getList(), subIDMap);
			fTree.getChildren().add(tree);
		}
	}
	/**
	 * 栏目未更新，保存栏目选择
	 * @param parameters
	 * @throws Exception
	 */
	public void save_SubjectEmployee(ParametersUtil parameters) throws Exception {
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("eids") == null){
			throw new BusinessException(depict + "获取缺少用户ID参数!");
		}
		if(objectMap.get("qxlx") == null){
			throw new BusinessException(depict + "获取缺少权限类型参数!");
		}
		//先清空当前角色的类型权限信息
		String qxlx = objectMap.get("qxlx").toString();
		ArrayList<String> edir = (ArrayList<String>) objectMap.get("eids");
		for(String eid : edir){
			objectDao.executeSql("delete from B_subjectcheck where CheckType = '" + qxlx + 
					"' and CompanyID = '" + objectMap.get("id") + "' and employeeid = '"+eid+"'");
			ArrayList<String> dir = (ArrayList<String>) objectMap.get("sids");
			String qxid = objectMap.get("id").toString();
			//循环将新权限保存进去
			for (String id : dir) {
				B_subjectcheck obj = new B_subjectcheck();
				obj.setId(this.getUUID());
				obj.setCompanyid(qxid);
				obj.setChecktype(qxlx);
				String[] ids = id.split("--");
				obj.setSubjectid(ids[0]);
				obj.setBaseid("0");
				obj.setEmployeeid(eid);
				objectDao.save(obj);
		}
		}
	}
	
	/**
	 * 根据角色ID集合获取所属权限ID集合
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public Map<String, List<String>> getCheckByRoleIds(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("ids") == null){
			throw new BusinessException(depict + "获取缺少角色ID参数!");
		}
		ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");
		String sql = "";
		if(idList.size() == 1){
			sql = "t.employeeid = '" + idList.get(0) + "'";
		}else{
			for (String id : idList) {
				if (!"".equals(sql)){
					sql += ",";
				}
				sql += "'" + id + "'";
			}
			sql = "t.employeeid in (" + sql + ")";
		}
		Map<String, List<String>> popedomMap = new HashMap<String, List<String>>();
		popedomMap.put(jclxlmglry, new ArrayList<String>());
		List<B_subjectcheck> groupList = objectDao.queryByHql("from B_subjectcheck t where 1 = 1 and " + sql);
		
		for (B_subjectcheck obj : groupList) {
			if (popedomMap.containsKey(obj.getChecktype())){
				if (popedomMap.get(obj.getChecktype()).indexOf(obj.getSubjectid()) == -1){
					popedomMap.get(obj.getChecktype()).add(obj.getSubjectid());
				}
			}
		}
		return popedomMap;
	}
}
